package handler

import (
	"boat-manager/cache"
	"boat-manager/models"
	"boat-manager/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	var user models.User
	redis_user_key := "redis_user_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_user_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次",
		})
		return
	}
	err := models.DB.Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.MD5(password) {

		cache.Rdb.Set(cache.Ctx, redis_user_key, 3, time.Hour*2)
		if errCount == 2 {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
func List(c *gin.Context) {
	var list []models.User
	redis_list_key := "redis_list"
	Count, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if Count == "" {
		models.DB.Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(Count), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var list []models.User
	redis_detail_key := "redis_detail" + id
	Count, _ := cache.Rdb.Get(cache.Ctx, redis_detail_key).Result()
	if Count == "" {
		models.DB.Where("id = ?", id).Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_detail_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(Count), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}
